/**
* @Title: institution_detail_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @author EX-chenyonghong001
* @date 2014年10月17日 下午2:38:47
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('institutionDetailOtherCtrl', ['$scope','$modal','CommunityService','$http','$state','$stateParams','institutionDetailService','BaseService','BaseURL','Modal',
	                                function($scope,$modal,CommunityService,$http,$state,$stateParams,institutionDetailService,BaseService,baseUrl,Modal){
 
		$scope.communityService = CommunityService;
	//	 CommunityService.getBaseCode('{codeType:\'orgType\',orgTypeCode:\'0\'}');
		 CommunityService.getBaseCode('{codeType:\'pointType\'}');
		 CommunityService.getBaseCode('{codeType:\'orgLevel\'}');
		 CommunityService.getBaseCode('{codeType:\'medicalPro\'}');
		 CommunityService.getBaseCode('{codeType:\'classificationType\'}');
		 CommunityService.getBaseCode('{codeType:\'openBusiness\'}');
		 CommunityService.getBaseCode('{codeType:\'economicType\'}');
		 CommunityService.getBaseCode('{codeType:\'region\',codeNo:\'-1\',regionType:\'1\'}');
		 CommunityService.getBaseCode('{codeType:\'provincialDep\'}');
		 CommunityService.initCodeListDatas();
		 
			/**医疗机构类别*/
		 $scope.UrlParams = $stateParams;
		 var providerid = $scope.UrlParams.providerid;
		 var providerCode = "";
		var type =$scope.UrlParams.type;
        $scope.authority={
        		add:1,
        		update:1,
        		deleted:1
        }
        var workDepCellTemplate = 
			'<td>'+
			'<a ng-init="dataInit=data.workDep" ng-click="queryRelation(data)">{{dataInit}}</a>'+
			'</td>';
		$scope.columns = [ 
		{
		    label : '医院科室',
		    map : 'workDep',
		    width : '20%',
		    cellTemplate:workDepCellTemplate
		    }, {
			label : '省科室',
			map : 'department',
			width : '20%'
		}, {
			label : '联系人',
			map : 'contacts',
			width : '20%'
//			cellTemplate:cellTemplate
		}, {
			label : '手机',
			map : 'moblie',
			width : '20%'
		}
		, {
			label : '联系电话',
			map : 'phone',
			width : '20%'
		}];
    		
        $scope.institutionList={};
        $scope.institutionDetail={};
        $scope.tableData =[];
        $scope.contactList =[];
        var name = "";
        var addr = "";
        var lealPerson = "";
        
        $scope.deleteCode = function(data){
        	return data.code !='10';
        }

        $scope.deleteTypeCode = function(data){
        	return data.code !='51';
        }
        
        $scope.inputChange = function(){
        	
        if($scope.institutionDetail.startPeriod && $scope.institutionDetail.endPeriod){
        	if($scope.institutionDetail.startPeriod>$scope.institutionDetail.endPeriod){
             	 Modal.alert('执业有效期开始日期不得大于结束日期！');
               return;
          }else if($scope.institutionDetail.pointStartdate>$scope.institutionDetail.pointEnddate){
             	 Modal.alert('定点期限开始日期不得大于结束日期！');
               return;
          }
        }

        }
        $scope.onSubmit = function(){
        	var providerid =$scope.UrlParams.providerid;
        	if(providerid){
	            var params = {providerid:providerid};
	            
	            institutionDetailService.query(params).success(function(res){
	            $scope.tableData = res.contact;
	            $scope.relationDetail2 = res.contacts;
	            $scope.relationDetail1 = res.responsible;
	            $scope.institutionDetail = res.result;
	    		$scope.authority=res.authority;
	          	var temp = [];
	          	var pointType = $scope.institutionDetail.pointType;
	      		if(pointType){
	      			pointType = pointType.split(',');
	      		}
				angular.forEach(pointType,function(pointType,v){
					var code = {codeno:pointType};
					temp.push(code);
				});
				$scope.institutionDetail.pointType1 = temp;
				var openBusiness = $scope.institutionDetail.openBusiness;
				temp = [];
				if(openBusiness){
					openBusiness = openBusiness.split(',');
	      		}
				angular.forEach(openBusiness,function(openBusiness,v){
					var code = {codeno:openBusiness};
					temp.push(code);
				});
				$scope.institutionDetail.openBusiness1 = temp;
				var openBusiness = $scope.institutionDetail.openB
				name = $scope.institutionDetail.providerName;
	          	addr = $scope.institutionDetail.fullAddress;
	          	lealPerson = $scope.institutionDetail.lealPerson;
	          	providerCode= $scope.institutionDetail.providerCode;
				});
        	}
        };

        $scope.updateName={};
        //监控名称
        $scope.$watch("institutionDetail.providerName",function(newVal,oldVal){
        	if(newVal && oldVal && newVal != name){
        		 $scope.updateName ={
        				 relationid:$scope.UrlParams.providerid,
        				 changeContent:"医院名称",
        				 changeBefore:name,
        				 changeAfter:newVal,
        				 changeType:0
        		 }
        	}else{
        		$scope.updateName ={};
        	}
        	
        });
          //监控地址
              $scope.updateFullAddress={};
         $scope.$watch("institutionDetail.fullAddress",function(newVal,oldVal){
        	if(newVal && oldVal && newVal != addr){
        		 $scope.updateFullAddress ={
        				 relationid:$scope.UrlParams.providerid,
        				 changeContent:"地址",
        				 changeBefore:addr,
        				 changeAfter:newVal,
        				 changeType:0
        		 }
        	}else{
        		$scope.updateFullAddress ={};
        	}
        	
        });
        //监控法人代表
        $scope.updateLealPerson={};
        $scope.$watch("institutionDetail.lealPerson",function(newVal,oldVal){
        	if(newVal && oldVal && newVal != lealPerson){
        		 $scope.updateLealPerson ={
        				 relationid:$scope.UrlParams.providerid,
        				 changeContent:"法人代表",
        				 changeBefore:lealPerson,
        				 changeAfter:newVal,
        				 changeType:0
        		 }
        	}else{
        		$scope.updateLealPerson ={};
        	}
        	
        });
        
		//获取代码表code集合
		$scope.getFieldCodes = function(datas){
			var codes = [];
			angular.forEach(datas,function(data,i){
				codes.push(data.codeno);
			});
			return codes.join(",");
		};

		
		$scope.checkRelation = function(relationDetail,type){
			if(!relationDetail.contacts&&type==1){
				return "医保负责人不能为空！";
			}
			if(!relationDetail.contacts&&type==2){
				return "医保联系人不能为空！";
			}
			if(!relationDetail.moblie){
				return "手机不能为空！";
			}
			if(!relationDetail.phone){
				return "电话不能为空！";
			}
		}
        /**
         * 机构详细信息--新增
         * @param params
         */
	    var contactList =[];
    	var ruleArray ='';
        $scope.saveOrUpadate = function(newtype){
        	if(type==1){
        		$scope.institutionDetail.organizationType = "51";
        	}
        	if(!providerid && contactList){
       		 angular.forEach($scope.communityService.dictionaryMap['provincialDep'],function(map,v){
       			 angular.forEach(contactList,function(contactList,v){
						if(contactList.department == map.codename){
							contactList.departmentNo =map.codeno;
						}
					});	
       		 
       		 });
        		$scope.institutionDetail.contactList =contactList; 
        	}
        	
            var updateList=[];
        	var pointType = $scope.institutionDetail.pointType1;
			if(pointType)
			{
				$scope.institutionDetail.pointType =$scope.getFieldCodes(pointType);
			}
			var openBusiness = $scope.institutionDetail.openBusiness1;
			if(openBusiness)
			{
				$scope.institutionDetail.openBusiness =$scope.getFieldCodes(openBusiness);
			}
        	var params = $scope.institutionDetail; 
        	if($scope.updateName.relationid){
        		updateList.push($scope.updateName);
        		//$scope.updateName ={};
        	}
        	if($scope.updateFullAddress.relationid){
       		updateList.push($scope.updateFullAddress);
       	//	$scope.updateFullAddress ={};
        	}
        	if($scope.updateLealPerson.relationid){
       		updateList.push($scope.updateLealPerson);
       		//$scope.updateLealPerson ={};
        	}
	       	 params.relationDetail1 = $scope.relationDetail1;
	    	 params.relationDetail2 = $scope.relationDetail2;
    
	    	
        	params.updateList = updateList;
        	params.providertype = newtype;
            if(formart()) {
                $http.post(baseUrl + '/hcpms/provider/save.do', params).success(function (data) {
                    if (data.state == 0) {
                        //	$scope.institutionDetail.pointType =pointType;
                        Modal.alert(data.msg);
                        //$scope.onSubmit();
                        if(data.providerId){
                        	 $scope.institutionDetail.providerId = data.providerId;
                        	 $scope.UrlParams.providerid=data.providerId;
                        }
                        $state.go('institutionInfoOther.institutionOther');
                       
                       
                    }else{
                    	  Modal.alert(data.errors);
                    }
                
                })
            	
            }
    	
        };
        //校验必填项
            function check(newtype)
            {
                if(!$scope.institutionDetail.providerName)
                {
                    Modal.alert('医疗机构名称为必填项！');
                    return false;
                }else  if(newtype!='1' && !$scope.institutionDetail.hospitalLevel)
                {
                    Modal.alert('医院等级为必填项！');
                    return false;
                }else  if(newtype!='1' &&!$scope.institutionDetail.organizationType)
                {
                    Modal.alert('卫生机构类别为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.managementCode)
                {
                    Modal.alert('经营性质为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.organizationCode)
                {
                    Modal.alert('组织机构代码为必填项！');
                    return false;
                }else  if(newtype!='1' && !$scope.institutionDetail.bednum)
                {
                    Modal.alert('床位数为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.fileNo)
                {
                    Modal.alert('文件号为必填项！');
                    return false;
                }else  if($scope.institutionDetail.pointType1.length==0)
                {
                    Modal.alert('定点类别为必填项！');
                    return false;
                }else  if($scope.institutionDetail.openBusiness1.length==0)
                {
                    Modal.alert('开通业务为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.lealPerson)
                {
                    Modal.alert('法人代表为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.addressCounty)
                {
                    Modal.alert('所在地区为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.fullAddress)
                {
                    Modal.alert('详细地址为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.practiceLicense)
                {
                    Modal.alert('执业许可证为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.startPeriod || !$scope.institutionDetail.endPeriod)
                {
                    Modal.alert('执业有效期为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.clinicalSubjects)
                {
                    Modal.alert('诊疗科目为必填项！');
                    return false;
                }else  if(!$scope.institutionDetail.pointStartdate)
                {
                    Modal.alert('请选择定点开始日期！');
                    return false;
                }else  if(newtype=='0' &&$scope.institutionDetail.hospitalLevel=="10")
                {
                    Modal.alert('医院等级不能选择药店！');
                    return false;
                }else  if(newtype=='0' &&$scope.institutionDetail.organizationType=="51")
                {
                    Modal.alert('机构类别不能选择药店！');
                    return false;
                }else
                {
                    return true;
                }
            };
            function formart()
            {
                var numTest = /^[0-9]{0,10}$/;
                var money= /^[0-9]{0,10}(\.?[0-9]{2})$/;
                var a=/^[0-9]{6}$/;
                var email= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                var reg =/^\d{4}-\d{2}-\d{2}$/; 
                if($scope.institutionDetail.bednum && !numTest.test($scope.institutionDetail.bednum))
                {
                    Modal.alert('床位数为十位数以内的整数！');
                    return false;
                }else if($scope.institutionDetail.registerFund && !money.test($scope.institutionDetail.registerFund))
                {
                    Modal.alert('注册资金为十位数以内的数字！');
                    return false;
                }else if($scope.institutionDetail.postcode && !a.test($scope.institutionDetail.postcode))
                {
                    Modal.alert('邮政编码为六位数字！');
                    return false;
                }else if($scope.institutionDetail.mail && !email.test($scope.institutionDetail.mail))
                {
                    Modal.alert('电子邮箱输入有误！');
                    return false;
                }else if(!reg.test($scope.institutionDetail.pointEnddate) &&  !reg.test($scope.institutionDetail.pointStartdate)){
                	 Modal.alert('定点期限格式输入有误！');
                     return false;
                }else if(!reg.test($scope.institutionDetail.startPeriod) &&  !reg.test($scope.institutionDetail.endPeriod)){
	               	 Modal.alert('执业有效期格式输入有误！');
	                 return false;
                }else if($scope.institutionDetail.startPeriod>$scope.institutionDetail.endPeriod){
	               	 Modal.alert('执业有效期开始日期不得大于结束日期！');
	                 return false;
                }else if($scope.institutionDetail.pointEnddate&&$scope.institutionDetail.pointStartdate>$scope.institutionDetail.pointEnddate){
	               	 Modal.alert('定点期限开始日期不得大于结束日期！');
	                 return false;
                }
                return true;
            };

           $scope.cancel=function(type)
           {
               if(type!='1')
               {
                   $state.go("institutionInfoOther.institutionOther");
               }else
               {

                   $state.go("institutionInfoOther.pharmacyOther");
               }

           };

        $scope.updateProvider = function(){
        	 $scope.institutionDetail.relationDetail1 = $scope.relationDetail1;
        	 $scope.institutionDetail.relationDetail2 = $scope.relationDetail2;
        	var params = $scope.institutionDetail; 
        	
	  		$http.post(baseUrl + '/hcpms/provider/save.do',params).success(function(data) {
	  		})
        };
        /**
         * 查询修改记录
         * @param params
         */
        $scope.queryChange = function (){
        	var params = {providerid:$scope.UrlParams.providerid};
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institutionOther/change_info.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  
				  $scope.columns = [ 
				     {
						label : '序号',
						map : '$index',
						width : '10%',
						 cellTemplate:'<span ng-bind="$index + 1"></span>'
				     },{
                          label : '变更日期',
                          map : 'applicantionDate',
                          width : '20%'
                      }, {
						label : '变更内容',
						map : 'changeContent',
						width : '20%'
					}, {
						label : '变更前',
						map : 'changeBefore',
						width : '25%'
					}, {
						label : '变更后',
						map : 'changeAfter',
						width : '25%'
					}];
				  
						$http({
							method : 'GET',
							cache : false,
							url : baseUrl + '/hcpms/provider/changeRecord.do',
							params :  params
						}).success(function(response, status, headers, config) {
							$scope.tableData = response.result;
						});
						
					
				 //关闭model
				 $scope.onClose = function() {
					$modalInstance.close();
				 }
				}
		    });
		
        };
        if(providerid){
            $scope.onSubmit();
        }else{
        	 institutionDetailService.getProviderCode().success(function(res){
        		 $scope.institutionDetail.providerCode = res.providerCode;
        		 $scope.authority=res.authority;
        	 })
        };
        /**
         * 联系人--查询
         * @param params
         */
        $scope.queryRelation = function (data){
        	var dictionaryMap = $scope.communityService.dictionaryMap;
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institutionOther/relation_info_add.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  $scope.dictionaryMap = dictionaryMap;
				  $scope.relationDetail = {};
					 angular.forEach(dictionaryMap['provincialDep'],function(map,v){
						 if(map.codename ==  data.department){
							 data.departmentNo = map.codeno;
						 }
		       		 });
							$scope.relationDetail = data;
						
							var numTest = /^[0-9]{0,20}$/;
						$scope.checkParms = function(relationDetail) { 
							if(!relationDetail.departmentNo){
								return "科室不能为空！";
							}
							if(!relationDetail.contacts){
								return "联系人不能为空！";
							}
							if(!relationDetail.phone){
								return "联系电话不能为空！";
							}
							return "";
						};
						$scope.match = function(relationDetail) { 
							if(relationDetail.moblie && !numTest.test(relationDetail.moblie)){
								return "手机号码必须为数字！";
							}
							if(relationDetail.phone && !numTest.test(relationDetail.phone)){
								return "联系电话必须为数字！";
							}
							return "";
						};
						
						$scope.add = function() {
							var checkMsg = $scope.checkParms($scope.relationDetail);
							var matchMsg = $scope.match($scope.relationDetail);
							if(checkMsg){
								 Modal.alert(checkMsg);
								 return;
							}
							if(matchMsg){
								 Modal.alert(matchMsg);
								 return;
							}
							 $http.post(baseUrl + '/hcp/hcp/contact/update.do', $scope.relationDetail).success(function(data) {
	                             if(data.state=='0')
	                             {
	                                 Modal.alert(data.msg);
	                                 $modalInstance.close();
	                             }else
	                             {
	                                 Modal.alert("修改失败！");
	                                 $modalInstance.close();
	                             }

	                         })
						
							
						}
					
				 //关闭model
				 $scope.onClose = function() {
					$modalInstance.close();
				 }
				}
		    });
		    modalInstance.result.then(function (selectedItem) {
		    		$scope.onSubmit();
		    });
		
        };
        
        /**
         * 联系人--新增
         * @param params
         */
		//打开日期Model
		$scope.addRelation = function () {
			var id =  providerCode;
			  CommunityService.getBaseCode('{codeType:\'provincialDep\'}');
			var dictionaryMap = $scope.communityService.dictionaryMap;
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institutionOther/relation_info_add.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  $scope.dictionaryMap = dictionaryMap;
				  $scope.relationDetail = {};
				  $scope.relationDetail.providerid = id;
				  $scope.check = function(relationDetail) {
					  if(!relationDetail.contacts){
						  return "联系人不能为空！";					  
					  }
					  if(!relationDetail.departmentNo){
						  return "科室不能为空！";					  
					  }
					  if(!relationDetail.phone){
						  return "联系电话不能为空！";					  
					  }
   				  }
				  var numTest = /^[0-9]{0,20}$/;
					$scope.match = function(relationDetail) { 
						if(relationDetail.moblie && !numTest.test(relationDetail.moblie)){
							return "手机号码必须为数字！";
						}
						if(relationDetail.phone && !numTest.test(relationDetail.phone)){
							return "联系电话必须为数字！";
						}
						return "";
					};
					$scope.add = function() {
						
						var matchMsg = $scope.match($scope.relationDetail);
						if(matchMsg){
							 Modal.alert(matchMsg);
							 return;
						}
						 if($scope.check($scope.relationDetail)){
							 Modal.alert($scope.check($scope.relationDetail));
							 return;
						 }
						 if(id){
							 $http.post(baseUrl + '/hcp/hcp/contact/create.do', $scope.relationDetail).success(function(data) {
	                             if(data.state=='0')
	                             {
	                                 Modal.alert("新增成功！");
	                                 $scope.onClose();
	                                 $modalInstance.close();
	                             }else
	                             {
	                                 Modal.alert("新增失败！");
	                                 $modalInstance.close();
	                             }

	                         })
						 }else{
							 var relationDetail = $scope.relationDetail;
							 var relationDetailBak = relationDetail;
							 var department = relationDetail.departmentNo;
							 angular.forEach($scope.dictionaryMap['provincialDep'],function(map,v){
									if(department == map.codeno){
										relationDetailBak.department =map.codename;
									}
								});
							 $modalInstance.close(relationDetailBak);
						 }
			
					
						
					}
					
					
				 //关闭model
				 $scope.onClose = function( ) {
					$modalInstance.close();
				 }
				}
		    });
		
		    modalInstance.result.then(function (arr) {
		    	if(arr){
		    		var relationDetail = arr;
		    		$scope.getContactList(relationDetail);
		    
		    	}else{
		    		if(providerid){
		    		  	var params = {providerid:providerCode};
				    	 institutionDetailService.queryContactList(params).success(function(res){
				    		    $scope.tableData = res.result;
				    	 });
		    		}
		    	}
		  
		    	 
		    });
		    
			$scope.getContactList = function (relationDetail){
				$scope.tableData.push(relationDetail);
	    		contactList.push(relationDetail);
			}
		};
		

		
		
	    $scope.checkRows = [];
        function findCheck(d) {
            for(var i=0;i< $scope.checkRows .length;i++) {
                var checkedData =  $scope.checkRows [i];
                if(checkedData.itemId == d.itemId) {
                    return i;
                }
            }
            return -1;
        };

        $scope.$on('fwatable.checked', function(e,d){
            if(findCheck(d) == -1) {
                $scope.checkRows .push(d);
            }
        });

        $scope.$on('fwatable.unchecked', function(e,d){
            var index = findCheck(d);
            if(index != -1) {
                $scope.checkRows.splice(index,1);
            }
        });
        /**
         *删除联系人
         * @param params
         */
        $scope.deleteRelation = function(){
            var	checkRows =  $scope.checkRows;
            if (checkRows.length == 0) {
                Modal.alert("请勾选删除项！");
                return;
            }else
            {
                var ids = '';
                angular.forEach(checkRows,function(totalCheck,i){
                    ids+="'"+totalCheck.id+"',";
                });
                var  params= {
                ids : ids
                }
                Modal.confirm('确认删除吗？',function() {
                	if(providerid){
                	      $http.post(baseUrl + '/hcp/hcp/contact/delete.do', params).success(function (data) {
                              if (data.state == '0') {
                                 Modal.alert("删除成功！");
                              } else {
                                  Modal.alert("删除失败！");
                              }
                              $scope.onSubmit();
                          })
                	}else{
                		var tempData = [];
                		  angular.forEach($scope.tableData,function(totalCheck,i){
                          	if(!totalCheck.checked){
                          		tempData.push(totalCheck);
                          	}
                          });
                		  $scope.tableData=tempData;
                	}
                  
                	
              
                })
            }
        };

    }
	]);
})();